/*
 *             Copyright (C) 2024 Steve Jrong
 *
 * 	   GitHub Homepage: https://www.github.com/SteveJrong
 *      Gitee Homepage: https://gitee.com/stevejrong1024
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stevejrong.waiter.mq.message.component;

import java.util.List;

import org.apache.rocketmq.client.consumer.MQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.context.SmartLifecycle;

import com.stevejrong.waiter.common.component.log.LogUtil;
import com.stevejrong.waiter.common.component.util.SpringUtil;

import jakarta.validation.constraints.NotNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 基类 - 领域事件监听器
 * <p>
 * 所有领域事件的监听器都要继承此类，并重写其内的所有抽象方法。
 *
 * @author Steve Jrong
 * @since 1.0
 */
@Slf4j
public abstract class AbstractEventHandler implements MessageListenerConcurrently, SmartLifecycle {

    /**
     * 设置消费者的Bean名称
     *
     * @return 消费者的Bean名称
     */
    protected abstract String setConsumerBeanName();

    @SneakyThrows
    @Override
    public void start() {
        MQPushConsumer consumer = SpringUtil.getBean(setConsumerBeanName());
        consumer.registerMessageListener(this);
        consumer.start();
    }

    @Override
    public boolean isAutoStartup() {
        return SmartLifecycle.super.isAutoStartup();
    }

    @Override
    public void stop(@NotNull Runnable callback) {
        SmartLifecycle.super.stop(callback);
    }

    @Override
    public int getPhase() {
        return SmartLifecycle.super.getPhase();
    }

    @Override
    public void stop() {
    }

    @Override
    public boolean isRunning() {
        return false;
    }

    /**
     * 消费消息
     *
     * @param messageExtList 扩展消息列表，是客户端从Broker（针对非广播消息）或本地（针对广播消息）拉取到的待消费的消息
     * @param context        消费上下文对象
     * @return <ul>
     * <li>ConsumeConcurrentlyStatus.CONSUME_SUCCESS - 消息消费成功，并从消息队列中移除此消息。</li>
     * <li>ConsumeConcurrentlyStatus.RECONSUME_LATER - 消息消费失败，并在稍后会重新投递此消息以再次消费。</li>
     * </ul>
     */
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messageExtList, ConsumeConcurrentlyContext context) {
        int index = 0;

        try {
            while (index < messageExtList.size()) {
                MessageExt currentMessageExt = messageExtList.get(index);
                String currentMessage = new String(currentMessageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);

                log.info(LogUtil.builder().append(this.getClass().getName() + "_consumeMessage", "集群模式消费到消息")
                        .append("currentMessage", currentMessage).toString());
                consume(currentMessageExt);
                index++;
            }
        } catch (Exception e) {
            log.error(LogUtil.builder().append(this.getClass().getName() + "_consumeMessage", "集群模式消费消息异常")
                    .append("exception", e.getMessage()).toString());

            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        } finally {
            if (index < messageExtList.size()) {
                context.setAckIndex(index + 1);
            }
        }

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    /**
     * 子类消费消息
     *
     * @param messageExt 扩展消息
     */
    protected abstract void consume(MessageExt messageExt);
}